from django.contrib.auth.decorators import permission_required
from django.http import HttpResponse
from django.db.models import Max
from django.shortcuts import render_to_response
from django.template import RequestContext
from lotto.service.load import *
from lotto.service.update import *
from lotto.catalog.models import *
from lotto.const import GAME
try:
    import simplejson
except ImportError:
    import json


def next (cls):
    return int(cls.objects.all ().aggregate (Max ('id'))['id__max']) + 1;


@permission_required ('is_superuser')
def load (request):
    message = [load_lotto (), load_mini (), load_multi (), load_joker (), load_kaskada ()];
    return render_to_response ('info.html',
							   {'title':'Import danych', 'msg': message},
							   context_instance = RequestContext (request));


@permission_required ('is_superuser')
def update (request):
    message = [parse_lotto (next (Lotto)), parse_mini (next (MiniLotto)),
               parse_multi (next (MultiMulti)), parse_joker (next (Joker)),
               parse_kaskada (next (Kaskada))];
    return render_to_response ('info.html',
							   {'title':'Aktualizacja danych', 'msg': message},
							   context_instance = RequestContext (request));


def service (request, mode):
    try:
        lotto = GAME[mode].objects.latest ('id');
        x = simplejson.dumps ({'id':lotto.id, 'date':lotto.date.strftime ('%d-%m-%Y'), 'nums':lotto.as_list ()});
        return HttpResponse (x);
    except:
        return HttpResponse ('["Error"]');
